/*
 * hkh-project
 * leafteamwork.blogspot.com
 * Tool: Netbeans 6.7.1 - SQL Server 2005
 */
package vn.com.hkh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.com.hkh.dto.PageDTO;
import vn.com.hkh.dto.UserDTO;
import vn.com.hkh.service.PageService;
import vn.com.hkh.util.DatabaseUtil;

/**
 *
 * @author leaf
 */
public class PageAction extends HttpServlet {

    private PageService ps = null;

    @Override
    public void init() throws ServletException {
        super.init();
        ps = new PageService();
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String forward = "";

        PrintWriter out = response.getWriter();
        try {
            String _message = "";
            if (request.getSession().getAttribute("login") == null) {
                _message = "Please login!";
                request.setAttribute("message", _message);
                RequestDispatcher rd = request.getRequestDispatcher("/LoginAction");
                rd.forward(request, response);
            } else {
                // T01. CLIENT PROCESS
                String action = request.getParameter("act");
                action = (action == null) ? "list" : action;

                // T02. CRUD PROCESS
                if (action.equalsIgnoreCase("add")) {
                    PageDTO _pageDTO = new PageDTO();
                    //TODO: *** Add Page task
                    //request from pageadd
                    _pageDTO.setId(DatabaseUtil.generateUUID());
                    _pageDTO.setTitle(request.getParameter("title"));
                    _pageDTO.setContent(request.getParameter("content"));
                    _pageDTO.setAlias(request.getParameter("alias"));
                    _pageDTO.setPosition(Integer.parseInt(request.getParameter("position")));
                    _pageDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _pageDTO.setWhen(request.getParameter("when"));

                    UserDTO _userDTO = (UserDTO) request.getSession().getAttribute("login");
                    _pageDTO.setUser(_userDTO);

                    PageDTO _result = ps.create(_pageDTO);
                    if (_result == null) {
                        _message = "Add Error!";
                        request.setAttribute("room", _pageDTO);
                        action = "addform";
                    } else {
                        _message = "Add Successful!";
                        action = "list";
                    }
                } else if (action.equalsIgnoreCase("edit")) {
                    PageDTO _pageDTO = new PageDTO();
                    //TODO: *** Add Page task
                    //request from pageedit
                    _pageDTO.setId(request.getParameter("id"));
                    _pageDTO.setTitle(request.getParameter("title"));
                    _pageDTO.setContent(request.getParameter("content"));
                    _pageDTO.setAlias(request.getParameter("alias"));
                    _pageDTO.setPosition(Integer.parseInt(request.getParameter("position")));
                    _pageDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _pageDTO.setWhen(request.getParameter("when"));

                    UserDTO _userDTO = (UserDTO) request.getSession().getAttribute("login");
                    _pageDTO.setUser(_userDTO);

                    PageDTO _result = ps.store(_pageDTO);
                    if (_result == null) {
                        _message = "Update Error!";
                        request.setAttribute("page", _pageDTO);
                        action = "editform";
                    } else {
                        _message = "Update Successful!";
                        action = "list";
                    }
                } else if (action.equalsIgnoreCase("del")) {
                    String primaryKey = request.getParameter("pk");
                    boolean result = ps.remove(primaryKey);
                    _message = result ? "Delete Successful!" : "Delete Error!";
                    action = "list";
                } else if (action.equalsIgnoreCase("cancel")) {
                    action = "list";
                }
                // T03. FORWARD PROCESS
                if (action.equalsIgnoreCase("list")) {
                    Collection<PageDTO> _pageDTOs = ps.findPages();
                    request.setAttribute("pages", _pageDTOs);
                    forward = (_pageDTOs == null) ? "" : "/view/pagelist.jsp";
                } else if (action.equalsIgnoreCase("addform")) {
                    forward = "/view/pageadd.jsp";
                } else if (action.equalsIgnoreCase("editform")) {
                    PageDTO _pageDTO = (PageDTO) request.getAttribute("page");
                    if (_pageDTO == null) {
                        String _roomID = request.getParameter("pk");
                        _pageDTO = ps.findByPrimaryKey(_roomID);
                        _pageDTO.setWhen(DatabaseUtil.getYMD(_pageDTO.getWhen()));
                        request.setAttribute("page", _pageDTO);
                    }
                    forward = (_pageDTO == null) ? "" : "/view/pageedit.jsp";
                }

                //T04. LOOKUP & FORWARD TO VIEW
                request.setAttribute("from", "roomaction");
                request.setAttribute("message", _message);
                request.setAttribute("forward", forward);
                RequestDispatcher rd = request.getRequestDispatcher("/view/adminlayout.jsp");
                rd.forward(request, response);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void destroy() {
        super.destroy();
        ps = null;
    }
}
